package com.wangwenjun.concurrency.chapter14.atomicstampedreference;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Package: com.wangwenjun.concurrency.chapter14.atomicstampedreference
 * @ClassName: UseAtomicStampedReference02
 * @Author: lujieni
 * @Description: 使用AtomicStampedReference进行递增
 * @Date: 2021-03-22 10:02
 * @Version: 1.0
 */
public class UseAtomicStampedReference02 {

    public static void main(String[] args) throws Exception {
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(0,0);
        for(int i = 0;i < 10000;i++){
            new Thread(()->{
                while (true){
                    //int reference = atomicStampedReference.getReference(); //错误 compareAndSet会对int进行装箱就是不同的对象了
                    Integer reference = atomicStampedReference.getReference();//正确
                    int stamp = atomicStampedReference.getStamp();
                    if(atomicStampedReference.compareAndSet(reference,reference+1, stamp,stamp+1)){
                        break;
                    }
                }
            }).start();
        }

        Thread.sleep(3_000);

        System.out.println(atomicStampedReference.getReference());
    }
}